package cn.tedu.store.product.webapi.service.impl;

import cn.tedu.store.commons.pojo.product.dto.CategoryAddNewDTO;
import cn.tedu.store.commons.pojo.product.dto.CategoryUpdateDTO;
import cn.tedu.store.commons.pojo.product.entity.Category;
import cn.tedu.store.commons.pojo.product.vo.CategoryListItemVO;
import cn.tedu.store.commons.pojo.product.vo.CategoryStandardVO;
import cn.tedu.store.commons.ex.ServiceException;
import cn.tedu.store.commons.web.JsonPage;
import cn.tedu.store.product.webapi.mapper.BrandCategoryMapper;
import cn.tedu.store.product.webapi.mapper.CategoryAttributeTemplateMapper;
import cn.tedu.store.product.webapi.mapper.CategoryMapper;
import cn.tedu.store.product.webapi.mapper.SpuMapper;
import cn.tedu.store.product.service.ICategoryService;
import cn.tedu.store.commons.web.ServiceCode;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 分类业务接口实现类
 *
 * @author RelentlessFlow
 * @version 0.0.1
 */
@Slf4j
@Service
@DubboService
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BrandCategoryMapper brandCategoryMapper;
    @Autowired
    private CategoryAttributeTemplateMapper CATMapper;
    @Autowired
    private SpuMapper spuMapper;

    @Override
    public void addNew(CategoryAddNewDTO categoryAddNewDTO) {
        log.debug("开始处理[添加分类]业务 参数:{}", categoryAddNewDTO);
        int count = categoryMapper.countByName(categoryAddNewDTO.getName());
        if (count != 0) {
            String message = "添加失败,分类名称已被占用!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        log.debug("检查父类是否存在...");
        CategoryStandardVO parentCategory = categoryMapper.getStandardById(categoryAddNewDTO.getParentId());
        if (parentCategory == null) {
            String message = "添加失败,父类不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        //完善新分类数据
        log.debug("补充分类信息");
        int depth = parentCategory.getDepth() + 1;//当前分类深度是为父类深度+1;
        Category category = new Category();
        BeanUtils.copyProperties(categoryAddNewDTO, category);
        log.debug("depth:{}", depth);
        category.setDepth(depth);
        category.setIsParent(0);//默认无子类
        {
            int rows = categoryMapper.insert(category);
            if (rows != 1) {
                String message = "操作失败,服务器忙,请稍后再试!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_INSERT, message);
            }
        }

        //更新父类数据
        log.debug("准备更新关联的父类数据");
        if (parentCategory.getIsParent() == 0) {
            parentCategory.setIsParent(1);
            log.debug("父类isParent改为1");
        }
        Category pCategory = new Category();
        BeanUtils.copyProperties(parentCategory, pCategory);
        int rows = categoryMapper.updateById(pCategory);
        if (rows != 1) {
            String message = "操作失败,服务器忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("父类数据更新完成");
        log.debug("添加分类成功");
    }

    @Override
    public void delete(Long id) {
        log.debug("准备处理[删除分类]业务 参数:{}", id);
        CategoryStandardVO queryResult = categoryMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "删除分类失败,访问的资源不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        //检查是否有关联子类
        if (queryResult.getIsParent() != 0) {
            String message = "删除分类失败,当前分类存在关联子类!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        //检查是否有关联品牌
        {
            int count = brandCategoryMapper.countByCategory(id);
            if (count != 0) {
                String message = "删除分类失败,该分类存在关联的品牌!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        //检查是否有关联的属性模板
        {
            int count = CATMapper.countByCategory(id);
            if (count != 0) {
                String message = "删除分类失败,该分类存在关联的属性模板!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        //检查是否有关联的商品
        {
            int count = spuMapper.countByCategory(id);
            if (count != 0) {
                String message = "删除分类失败,该分类存在关联的商品!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        //执行删除
        int rows = categoryMapper.deleteById(id);
        if (rows != 1) {
            String message = "操作失败,服务器忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.debug("删除完成,准备检查关联父类的数据");
        //若删除的分类是原父类的最后子类,则原父类的isParent属性置0
        long parentId = queryResult.getParentId();
        int count = categoryMapper.countByParentId(parentId);
        if (count == 0) {
            log.debug("修改原父类数据");
            Category category = new Category();
            category.setId(parentId);
            category.setIsParent(0);
            int rowsUpdate = categoryMapper.updateById(category);
            if (rowsUpdate != 1) {
                String message = "修改父类数据失败,服务器忙,请稍后再试!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_UPDATE, message);
            }
        }
        log.debug("删除成功!");
    }

    @Override
    public void setEnable(Long id) {
        updateStatusById(id,1,"enable");
    }

    @Override
    public void setDisable(Long id) {
        updateStatusById(id,0,"enable");
    }

    @Override
    public void setDisplay(Long id) {
        updateStatusById(id,1,"display");
    }

    @Override
    public void setHidden(Long id) {
        updateStatusById(id,0,"display");
    }

    @Override
    public void updateById(Long id, CategoryUpdateDTO categoryUpdateDTO) {
        log.debug("开始处理[修改分类信息]业务 参数:{},{}", id, categoryUpdateDTO);
        CategoryStandardVO queryResult = categoryMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "修改分类失败,访问的资源不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        long oldParentId = queryResult.getParentId();//原父类的id
        long curParentId = categoryUpdateDTO.getParentId();//现父类的id
        CategoryStandardVO curParentCategory = categoryMapper.getStandardById(curParentId);//新父类
        //执行修改
        Category category = new Category();
        BeanUtils.copyProperties(categoryUpdateDTO, category);
        category.setId(id);
        category.setDepth(curParentCategory.getDepth() + 1);//更新深度
        int rows = categoryMapper.updateById(category);
        if (rows != 1) {
            String message = "操作失败,服务器忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("信息修改完成,准备更新现父类信息");
        //更新现父类信息
        if (curParentCategory.getIsParent() == 0) {
            category.setId(curParentId);
            category.setIsParent(1);
            rows = categoryMapper.updateById(category);
            if (rows != 1) {
                String message = "操作失败,服务器忙,请稍后再试!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_UPDATE, message);
            }
        }
        log.debug("现父类更新完成,准备更新原父类信息");
        //处理原父类信息
        {
            //检查新分类信息中的parentId是否改变
            if (curParentId != oldParentId) {
                int count = categoryMapper.countByParentId(oldParentId);
                if (count == 0) {//若原父类无子类
                    Category newCategory = new Category();
                    newCategory.setId(oldParentId);
                    newCategory.setIsParent(0);//改为非父级分类
                    rows = categoryMapper.updateById(newCategory);
                    if (rows != 1) {
                        String message = "操作失败,服务器忙,请稍后再试!";
                        log.warn(message);
                        throw new ServiceException(ServiceCode.ERR_UPDATE, message);
                    }
                }
            }
        }
    }

    @Override
    public CategoryStandardVO getStandardById(Long id) {
        log.debug("开始处理[获取分类详情]业务 参数:{}", id);
        CategoryStandardVO result = categoryMapper.getStandardById(id);
        if (result == null) {
            String message = "获取分类详情失败,访问的资源不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return result;
    }

    @Override
    public JsonPage<CategoryListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理[获取分类列表]业务");
        PageHelper.startPage(pageNum, pageSize);
        return JsonPage.restPage(categoryMapper.list());
    }

    @Override
    public List<CategoryListItemVO> portalList() {
        log.debug("开始处理[获取导航栏分类列表]业务");
        return categoryMapper.portalList();
    }

    @Override
    public JsonPage<CategoryListItemVO> listByParentId(Long parentId, Integer pageNum, Integer pageSize) {
        log.debug("开始处理[根据父类id获取分类列表]业务");
        PageHelper.startPage(pageNum, pageSize);
        return JsonPage.restPage(categoryMapper.listByParentId(parentId));
    }

    /*根据id改变分类状态*/
    private void updateStatusById(Long id, Integer value,String type){
        String[] enableTips = {"禁用","启用"};
        String[] showTips = {"隐藏","显示"};
        boolean flag = "enable".equals(type);
        String[] tips = flag?enableTips:showTips;
        CategoryStandardVO queryResult = categoryMapper.getStandardById(id);
        if(queryResult == null){
            String message = "设置"+tips[value]+"分类失败,该分类不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        if((flag?queryResult.getEnable():queryResult.getIsDisplay()) == value){
            String message = "设置"+tips[value]+"分类失败,该分类已经是"+tips[value]+"状态!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        Category category = new Category();
        category.setId(id);
        if(flag){
            category.setEnable(value);
        }
        else{
            category.setIsDisplay(value);
        }
        int rows = categoryMapper.updateById(category);
        if(rows != 1){
            String message = "操作失败,服务器忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
    }
}
